package com.haier.cloudremote.protocal;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.ArrayList;

import com.haier.cloudremote.common.SLog;
import com.haier.cloudremote.model.StateInfo;
import com.haier.cloudremote.model.StbInfo;
import com.haier.cloudremote.model.StbList;

public class SocketPackte {
	public DataOutputStream dos = null;

	public DataInputStream dis = null;

	// public PrintWriter pw=null;

	public Socket socket = null;

	public Socket createLongSocket() throws IOException{

		
		if (null != socket) {
			closeSocket();		
			socket = new Socket(ConnectManager.LOCAL_HOST, ConnectManager.PORT);			
		}
			
		if (null != socket) {
			dos = new DataOutputStream(socket.getOutputStream());
			dis = new DataInputStream(socket.getInputStream());
		} else {
			System.out.println("socket no create");
		}
	
		return socket;
	}
	
	public Socket getLongSocket() throws IOException{
		
		if (null == socket || socket.isClosed()) {
			socket = new Socket(ConnectManager.LOCAL_HOST, ConnectManager.PORT);			
		}
			
		if (null != socket) {
			dos = new DataOutputStream(socket.getOutputStream());// ByteArrayOutputStream()
			dis = new DataInputStream(socket.getInputStream());
		} else {
			System.out.println("socket no create");
		}
	
		return socket;
	}
	
	/**
	 * 获得活动的socket
	 * @return
	 * @throws IOException
	 * @throws ConnectException
	 */
	public Socket getShortSocket() throws IOException{
new Thread(){
	public void run() {
		
	};
}.start();
		if (null != socket) {
			socket.close();						
		}
			
		socket = new Socket(ConnectManager.LOCAL_HOST, ConnectManager.PORT);
		
		if (null != socket) {
			socket.setSoTimeout(10000);
			dos = new DataOutputStream(socket.getOutputStream());// ByteArrayOutputStream()
			dis = new DataInputStream(socket.getInputStream());
		} else {
			System.out.println("socket no create");
		}
	
		return socket;
	}

	
	public void closeSocket() {
		if (null != socket) {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (dis != null) {
			try {
				dis.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (dos != null) {
			try {
				dos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}		
		
	}

	// 发送数据包
	public void sendPacket(int cmd_ID, int messageId, ByteBuffer data) throws IOException {
		SLog.d("ssc", "sendPacket-----------------------");
			int pagaLenth = data.array().length;
			ByteBuffer b = ByteBuffer.allocate(16 + data.array().length);
			byte[] cmd = new byte[4];
			byte[] message = new byte[4];
			byte[] retain = new byte[4];
			byte[] packagelength = new byte[4];
			cmd = ConnectManager.intToByte(cmd_ID);
			message = ConnectManager.intToByte(messageId);
			retain = ConnectManager.intToByte(0);
			packagelength = ConnectManager.intToByte(pagaLenth);
			b.put(cmd);
			b.put(message);
			b.put(retain);
			b.put(packagelength);
			b.put(data.array());
			byte[] sb = b.array();
			SLog.d("ssc", "发送数据-----------------------");
			dos.write(sb);
			b.clear();
			dos.flush();
		
	}

	/**
	 * 读取遥控器学习过程的返回:长连接
	 * @return 返回码，正常情况下返回键值，否则返回错误码
	 * 	-1000 未知错误
	 * 	-2001 与CAE的连接断开
	 */
	public int reciveStudyPacket(){
		int cmd = 0;
		int msg = 0;
		int lenth = 0;
		int returnCode = -1000;
		int modenum = 0;
		byte tmp[] = new byte[4];
		try{		
			int len = dis.read(tmp);
			SLog.d("ssc", "len=="+len);
			if (len>0) {					
				cmd = ConnectManager.bytesToInt(tmp);
				if(cmd==ConnectManager.CMD_SSC_LEARN_RE){
					dis.read(tmp);
					msg = ConnectManager.bytesToInt(tmp);
					dis.read(tmp);
					dis.read(tmp);
					lenth = ConnectManager.bytesToInt(tmp);
					if(lenth>0){
						dis.read(tmp);
						returnCode = ConnectManager.bytesToInt(tmp);
						dis.read(tmp);
						switch (returnCode) {
						case 1001:// （用户有按键） 当UI收到这个消息时，提示用户按下一个匹配键
							modenum = ConnectManager.bytesToInt(tmp); 
							returnCode = modenum;
							break;
						default:
							break;
						}
						byte tmp16[] = new byte[16];
						dis.read(tmp16);
					}
							
				}	
			}else{
				try{
					socket.sendUrgentData(0xff);
				}catch (IOException e){//与CAE的socket连接中断，重试。。。
//					e.printStackTrace();
					System.out.println(e.getMessage());
					returnCode = -2001;	
					closeSocket();
				}
					
			}
					
		}catch (IOException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			System.out.println(e.getMessage());
			returnCode = -2001;	
			closeSocket();
		}
		
		

		return returnCode;
	}
	
	
	/**
	 * 读取返回的STB列表数据包
	 * @return
	 */
	public StbList receiveGetStbRe(){
		StbList stblist = new StbList();
		int cmd = 0;
		int msg = 0;
		int lenth = 0;

		try {
			byte tmp[] = new byte[4];
			int len = dis.read(tmp);
			if (len > 0) {// 有数据
				cmd = ConnectManager.bytesToInt(tmp);
				if(cmd == ConnectManager.CMD_SSC_GETSTBLIST_RE){
					len = dis.read(tmp);
					msg = ConnectManager.bytesToInt(tmp);
					len = dis.read(tmp);
					len = dis.read(tmp);
					lenth = ConnectManager.bytesToInt(tmp);
					if (lenth > 0) {
						// 返回码
						len = dis.read(tmp);
						stblist.setReturnCode(ConnectManager.bytesToInt(tmp));
						// 国家
						len = dis.read(tmp);
						stblist.setCountryId(ConnectManager.bytesToInt(tmp));
						// 省
						len = dis.read(tmp);
						stblist.setpId(ConnectManager.bytesToInt(tmp));
						// 城市
						len = dis.read(tmp);
						stblist.setCityId(ConnectManager.bytesToInt(tmp));
						// 区县
						len = dis.read(tmp);
						stblist.setTownId(ConnectManager.bytesToInt(tmp));
						// 推荐 类型个数
						ArrayList<StbInfo> stbInfos = new ArrayList<StbInfo>();
						StbInfo stbInfo;
						len = dis.read(tmp);
						int iCount = ConnectManager.bytesToInt(tmp);
						byte[] byte100 = new byte[100];
						for (int i = 0; i < iCount; i++) {
							stbInfo = new StbInfo();
							len = dis.read(tmp);
							stbInfo.setStbId(ConnectManager.bytesToInt(tmp));
							len = dis.read(byte100);
							stbInfo.setStbName(new String(byte100).trim());
							stbInfos.add(stbInfo);
						}
						stblist.setStbInfos(stbInfos);

					} else {
						stblist = null;
					}
				}
				
			}else{// 检查远程连接是否已断开
				try{
					socket.sendUrgentData(0xff);
				}catch (IOException e){//与CAE的socket连接中断，重试。。。
					e.printStackTrace();
//					System.out.println(e.getMessage());
					stblist = null;
					closeSocket();
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			stblist = null;
		}
		closeSocket();
		return stblist;
	}
	
	/**
	 * 读取用户选择的所用的机顶盒返回的数据包
	 * @return
	 */
	public int receiveSetStbRe(){
		int cmd = 0;
		int msg = 0;
		int lenth = 0;
		int returnCode = 0;
		int modenum = 0;
		int iReciveCode = -1003;
		byte tmp[] = new byte[4];
		
		int len;
		try {
			len = dis.read(tmp);
			if (len > 0) {
				cmd = ConnectManager.bytesToInt(tmp);
				if(cmd==ConnectManager.CMD_SSC_ON_USER_SELECTED_RE){
					len = dis.read(tmp);
					msg = ConnectManager.bytesToInt(tmp);
					len = dis.read(tmp);
					len = dis.read(tmp);
					lenth = ConnectManager.bytesToInt(tmp);
					if(lenth>0){// 包体
						len = dis.read(tmp);
						iReciveCode = ConnectManager.bytesToInt(tmp);
					}
//					byte tmp20[] = new byte[20];
//					dis.read(tmp20);
				}				
			} else {
				try{
					socket.sendUrgentData(0xff);
				}catch (IOException e){//与CAE的socket连接中断，重试。。。
					iReciveCode = -1003;
					closeSocket();
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			iReciveCode = -1003;
		}
		closeSocket();
		return iReciveCode;
	}
	
	/**
	 * 读取上传STB的返回数据包
	 * @return
	 */
	public int receiveUploadStbRe(){

		int cmd = 0;
		int msg = 0;
		int lenth = 0;
		int iReciveCode = -1000;
		byte tmp[] = new byte[4];
		
		int len;
		try {
			len = dis.read(tmp);
			if (len > 0) {
				cmd = ConnectManager.bytesToInt(tmp);
				if(cmd==ConnectManager.CMD_SSC_SHARE_KEYMAP_RE){
					len = dis.read(tmp);
					msg = ConnectManager.bytesToInt(tmp);
					len = dis.read(tmp);
					len = dis.read(tmp);
					lenth = ConnectManager.bytesToInt(tmp);
					if(lenth>0){// 包体
						len = dis.read(tmp);
						iReciveCode = ConnectManager.bytesToInt(tmp);
					}					
				}				
			} else {
				try{
					socket.sendUrgentData(0xff);
				}catch (IOException e){//与CAE的socket连接中断，重试。。。
					e.printStackTrace();
					iReciveCode = -1000;
					closeSocket();
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			iReciveCode = -1000;
		}
		closeSocket();
		return iReciveCode;
	
	}
	
	/**
	 * 读取获取SSC状态返回的数据包
	 * @return
	 */
	public StateInfo receiveGetSSCStateRe(){
		StateInfo stateInfo = null;
		int cmd = 0;
		int msg = 0;
		int lenth = 0;
		byte tmp[] = new byte[4];
		
		int len;
		try {
			len = dis.read(tmp);
			if (len > 0) {
				cmd = ConnectManager.bytesToInt(tmp);
				SLog.d("ssc", "cmd=="+cmd);
				if(cmd==ConnectManager.CMD_SSC_RETURN_STATUS_RE){
					dis.read(tmp);
					msg = ConnectManager.bytesToInt(tmp);
					dis.read(tmp);
					dis.read(tmp);
					lenth = ConnectManager.bytesToInt(tmp);
					SLog.d("ssc", "lenth<0");
					if (lenth > 0) {
						stateInfo = new StateInfo();
						dis.read(tmp);
//						SLog.d("ssc", "state type=="+ConnectManager.bytesToInt(tmp));
						stateInfo.setType(ConnectManager.bytesToInt(tmp));
						dis.read(tmp);
//						SLog.d("ssc", "state value=="+ConnectManager.bytesToInt(tmp));
						stateInfo.setValue(ConnectManager.bytesToInt(tmp));
					} else {
						stateInfo = null;
					}
					
				}	
			} else {
				try{
					socket.sendUrgentData(0xff);
				}catch (IOException e){//与CAE的socket连接中断，重试。。。
					stateInfo = null;
					closeSocket();
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			stateInfo = null;
		}
		closeSocket();
		return stateInfo;
	}
	
	/**
	 * 读取设置数据通道返回的数据包
	 * @return
	 */
	public int receiveSetChannelRe(){
		int cmd = 0;
		int msg = 0;
		int lenth = 0;
		int returnCode = 0;
		int modenum = 0;
		int iReciveCode = -1003;
		byte tmp[] = new byte[4];
		
		int len;
		try {
			len = dis.read(tmp);
			if (len > 0) {
				cmd = ConnectManager.bytesToInt(tmp);
				if(cmd==ConnectManager.CMD_SSC_ON_STB_CHANNEL_RE){
					len = dis.read(tmp);
					msg = ConnectManager.bytesToInt(tmp);
					len = dis.read(tmp);
					len = dis.read(tmp);
					lenth = ConnectManager.bytesToInt(tmp);
					if(lenth>0){// 包体
						len = dis.read(tmp);
						iReciveCode = ConnectManager.bytesToInt(tmp);
					}					
				}				
			} else {
				try{
					socket.sendUrgentData(0xff);
				}catch (IOException e){//与CAE的socket连接中断，重试。。。
					e.printStackTrace();
//					System.out.println(e.getMessage());
					iReciveCode = -1003;
					closeSocket();
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			iReciveCode = -1003;
		}
		
		closeSocket();
		return iReciveCode;
	}
	
	/**
	 * 读取用户设置是否开机启动机顶盒返回的数据包
	 * @return
	 */
	public int receiveSetBootSwitchRe(){
		int cmd = 0;
		int msg = 0;
		int lenth = 0;
		int returnCode = 0;
		int modenum = 0;
		int iReciveCode = -1003;
		byte tmp[] = new byte[4];
		
		int len;
		try {
			len = dis.read(tmp);
			if (len > 0) {
				cmd = ConnectManager.bytesToInt(tmp);
				if(cmd==ConnectManager.CMD_SSC_ON_STB_AUTO_ON_RE){
					len = dis.read(tmp);
					msg = ConnectManager.bytesToInt(tmp);
					len = dis.read(tmp);
					len = dis.read(tmp);
					lenth = ConnectManager.bytesToInt(tmp);
					if(lenth>0){// 包体
						len = dis.read(tmp);
						iReciveCode = ConnectManager.bytesToInt(tmp);
					}					
				}				
			} else {
				try{
					socket.sendUrgentData(0xff);
				}catch (IOException e){//与CAE的socket连接中断，重试。。。
					e.printStackTrace();
//					System.out.println(e.getMessage());
					iReciveCode = -1003;
					closeSocket();
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			iReciveCode = -1003;
		}
		closeSocket();
		return iReciveCode;
	}
	
	/**
	 * 读取测试STB返回的数据包
	 * @return
	 */
	public int receiveTestSTBRe(){
		int cmd = 0;
		int msg = 0;
		int lenth = 0;
		int returnCode = 0;
		int modenum = 0;
		int iReciveCode = -1003;
		byte tmp[] = new byte[4];
		
		int len;
		try {
			len = dis.read(tmp);
			if (len > 0) {
				cmd = ConnectManager.bytesToInt(tmp);
				if(cmd==ConnectManager.CMD_SSC_ON_TV_REMOTE_RE){
					len = dis.read(tmp);
					msg = ConnectManager.bytesToInt(tmp);
					len = dis.read(tmp);
					len = dis.read(tmp);
					lenth = ConnectManager.bytesToInt(tmp);
					if(lenth>0){// 包体
						len = dis.read(tmp);
						iReciveCode = ConnectManager.bytesToInt(tmp);
					}					
				}				
			} else {
				try{
					socket.sendUrgentData(0xff);
				}catch (IOException e){//与CAE的socket连接中断，重试。。。
					e.printStackTrace();
//					System.out.println(e.getMessage());
					iReciveCode = -1003;
					closeSocket();
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			iReciveCode = -1003;
		}
		closeSocket();
		return iReciveCode;
	}
	
	/**
	 * 读取设置debug开关返回的数据包
	 * @return
	 */
	public int receiveDebugSwitchRe(){
		int cmd = 0;
		int msg = 0;
		int lenth = 0;
		int returnCode = 0;
		int modenum = 0;
		int iReciveCode = -1003;
		byte tmp[] = new byte[4];
		
		int len;
		try {
			len = dis.read(tmp);
			if (len > 0) {
				cmd = ConnectManager.bytesToInt(tmp);
				if(cmd==ConnectManager.CMD_SSC_ON_DEBUG_RE){
					len = dis.read(tmp);
					msg = ConnectManager.bytesToInt(tmp);
					len = dis.read(tmp);
					len = dis.read(tmp);
					lenth = ConnectManager.bytesToInt(tmp);
					if(lenth>0){// 包体
						len = dis.read(tmp);
						iReciveCode = ConnectManager.bytesToInt(tmp);
					}					
				}				
			} else {
				try{
					socket.sendUrgentData(0xff);
				}catch (IOException e){//与CAE的socket连接中断，重试。。。
					iReciveCode = -1003;
					closeSocket();
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			iReciveCode = -1003;
		}
		closeSocket();
		return iReciveCode;
	}
	
	/**
	 * 读取获取文件路径返回的数据包
	 * @return
	 */
	public String receiveFilepathRe(){
		String filePath = null;
		int cmd = 0;
		int msg = 0;
		int lenth = 0;
		int returnCode = 0;
		int modenum = 0;
		int iReciveCode = -1003;
		byte tmp[] = new byte[4];
		
		int len;
		try {
			len = dis.read(tmp);
			if (len > 0) {
				cmd = ConnectManager.bytesToInt(tmp);
				if(cmd==ConnectManager.CMD_SSC_GET_SSCFILE_RE){
					dis.read(tmp);
					msg = ConnectManager.bytesToInt(tmp);
					dis.read(tmp);
					dis.read(tmp);
					lenth = ConnectManager.bytesToInt(tmp);
					if (lenth > 0) {
						dis.read(tmp);
						int getPathCode = ConnectManager.bytesToInt(tmp);
						switch (getPathCode) {
						case 1001:// 1001 成功
							byte tmp256[] = new byte[256];
							dis.read(tmp256);
							filePath = new String(tmp256);
							break;
						case -1000:// 其他错误
						default:
							filePath = null;
						}

					} else {
						filePath = null;
					}
				}				
			} else {
				try{
					socket.sendUrgentData(0xff);
				}catch (IOException e){//与CAE的socket连接中断，重试。。。
					filePath = null;
					closeSocket();
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			filePath = null;
		}
		closeSocket();
		return filePath;
	
	}

}
